package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.RuleListMapper;
import com.indusfo.spc.mapper.RuleMapper;
import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.pojo.Datadict;
import com.indusfo.spc.pojo.Rule;
import com.indusfo.spc.pojo.RuleList;
import com.indusfo.spc.service.RuleListService;
import com.indusfo.spc.untlis.StringUtils;
import com.indusfo.spc.vo.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author chenm
 * @create 2019-07-23 14:21
 */
@Service("ruleListService")
public class RuleListServiceImpl implements RuleListService {

    private static final Logger logger = LoggerFactory.getLogger(RuleListServiceImpl.class);

    @Resource
    private RuleListMapper ruleListMapper;

    @Resource
    private RuleMapper ruleMapper;
    @Resource
    private UploadMapper uploadMapper;
    /**
     * 新增
     *
     * @param ruleList
     * @return
     */
    @Override
    public JSONObject insertRuleList(RuleList ruleList) {
        try {
            if(ruleList.getRuleDetailId() != null){
                throw new ParamsErrorException("新增操作不能选择规则明细");
            }
            if(ruleList.getRuleId()==null){
                Rule rule=new Rule();
                List<Rule> rules = ruleMapper.listRule(rule);
                if(rules!=null){
                    Integer ruleId = rules.get(0).getRuleId();
                    ruleList.setRuleId(ruleId);
                }
            }
            checkParam(ruleList);

            int row = ruleListMapper.insertSelective(ruleList);
            if(row == 0){
                throw new ParamsErrorException("新增失败");
            }
            return JSONObject.oK("新增成功");
        }catch (GlobalException e){
            logger.error(e.getMessage(),e);
            return JSONObject.build(403,e.getMessage());
        }
    }

    /**
     * 删除
     *
     * @param ids
     * @param dataState
     * @return
     */
    @Override
    public JSONObject delRuleList(Integer[] ids, Integer dataState) {
        try{
            if(dataState == null){
                throw new ParamsErrorException("数据状态不能为空");
            }else if( dataState != 1 &&  dataState != 2 &&  dataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if(ids == null){
                throw new ParamsErrorException("请选择要删除的数据");
            }
            int row = ruleListMapper.delRuleList(ids,dataState);
            String msg= "";
            if(row == 0){
                switch (dataState){
                    case 1:
                        msg = "启用失败";
                        break;
                    case 2:
                        msg = "删除失败";
                        break;
                    case 3:
                        msg="停用失败";
                        break;
                }
            }else{
                switch (dataState){
                    case 1:
                        msg = "启用成功";
                        break;
                    case 2:
                        msg = "删除成功";
                        break;
                    case 3:
                        msg="停用成功";
                        break;
                }
            }
            return JSONObject.oK(msg);
        }catch (GlobalException e){
            logger.error(e.getMessage());
            return JSONObject.build(403,e.getMessage());
        }
    }

    /**
     * 修改
     *
     * @param ruleList
     */
    @Override
    public JSONObject updateRuleList(RuleList ruleList) {
        try {
            if(ruleList.getRuleDetailId() == null) {
                throw new ParamsErrorException("请选择要修改的数据");
            }
            if(ruleList.getRuleId() == null){
                throw new ParamsErrorException("请先选择条码规则");
            }
            checkParam(ruleList);
            int	row = ruleListMapper.updateByPrimaryKeySelective(ruleList);

            if(row == 0) {
                throw new ModifyFailedException("数据更新失败！");
            }
            return JSONObject.oK("更新成功！");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 查询
     *
     * @param ruleList
     */
    @Override
    public JSONObject queryRuleList(RuleList ruleList) {
        List<RuleList> ruleLists = null;
        try {
            Integer pagesize = ruleList.getPagesize();
            Integer pageindex = ruleList.getPageindex();
            if(pagesize != null && pageindex != null) {
                ruleList.setIncept(pagesize*(pageindex - 1));
            }
            Integer ruleListId = ruleList.getRuleDetailId();
            if(ruleListId != null) {  //如果有id,则查询单个信息
                ruleLists = ruleListMapper.getRuleList(ruleListId);
            } else{  //查询多个
                if(ruleList.getRuleId()==null){
                    Rule rule = new Rule();
                    List<Rule> list = ruleMapper.listRule(rule);
                    if(list != null && list.size() >= 1){
                        Rule rule1 = list.get(0);
                        ruleList.setRuleId(rule1.getRuleId());
                    }
                }
                ruleLists = ruleListMapper.listRules(ruleList);
            }
            if (ruleLists.isEmpty()) {
                return JSONObject.oK("没有相关数据", ruleLists, 0);
            }
            //查询分页总记录数
            int count = ruleListMapper.countRuleList(ruleList);
            return JSONObject.oK("查询成功", ruleLists, count);

        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }




    /**
     * 验证信息
     * @param ruleList
     */
    public void checkParam(RuleList ruleList){
        String remark = ruleList.getRemark();
        if(remark==null){
            remark="";
        }
        if(remark.length() > 100){
            throw new ParamsErrorException("备注字数超过规定,长度100");
        }
        /*if(ruleList.getRuleId() == null){
            throw new ParamsErrorException("请先选择条码规则");
        }*/
        if(ruleList.getCl() == null){
            throw new ParamsErrorException("请选择是否是常量");
        }
//        if(ruleList.getForm() == null){
//            throw new ParamsErrorException("请填写格式");
//        }
//        if (ruleList.getForm().length() > 50) {
//            throw new ParamsErrorException("格式字数超过规定,长度50");
//        }
//        if(ruleList.getType() == null){
//            throw new ParamsErrorException("请填写类型");
//        }
//        if (ruleList.getType().length() > 50) {
//            throw new ParamsErrorException("类型字数超过规定,长度50");
//        }
        /*if(ruleList.getAutoid() == null){
            throw new ParamsErrorException("请填写序号名");
        }
        if (ruleList.getAutoid().length() > 50) {
            throw new ParamsErrorException("序号名字数超过规定,长度50");
        }
        if(ruleListMapper.getRuleListAutoid(ruleList.getRuleDetailId(),ruleList.getAutoid()) != null){
            throw new ParamsErrorException("序号名称已存在");
        }*/

    }

    @Override
    public String checkNoRepeatExcel(RuleList ruleList) {
        //常量名称
        String clName = ruleList.getClName();
        //类型
        String type = ruleList.getType();
        //格式
        String form = ruleList.getForm();
        //条码规则类别名称
        String ruleName = ruleList.getRuleName();
        //初始值
        String first =ruleList.getFirst();
        //长度
        String len = ruleList.getLen();
        //步长
        String length =ruleList.getLength();
        //备注
        String remark =ruleList.getRemark();
        if(StringUtils.isBlank(first) && StringUtils.isBlank(clName) && StringUtils.isBlank(type) && StringUtils.isBlank(form) && StringUtils.isBlank(ruleName) &&
                StringUtils.isBlank(len) && StringUtils.isBlank(length) && StringUtils.isBlank(remark)){
            return "该行数据为空(原因:清空行内容时未清空彻底/未输入)";
        }
        if(ruleName==null){
            return "条码规则类别名称为空";
        }
        Map<String, Rule> ruleMap = uploadMapper.queryRule();
        if(!ruleMap.containsKey(ruleName)){
            return "条码规则类别名称输入错误/不规范";
        }
        Rule rule = ruleMap.get(ruleName);
        ruleList.setRuleId(rule.getRuleId());
        if(clName == null){
            return "常量选择为空";
        }
        if(!"是".equals(clName) && !"否".equals(clName)){
            return "常量选择输入错误/不规范";
        }
        if("是".equals(clName)){
            ruleList.setCl(1);
        }else if("否".equals(clName)){
            ruleList.setCl(0);
        }
        if(type!=null){
            Map<String, Datadict> typeMap = uploadMapper.queryType(101037);
            if(!typeMap.containsKey(type)){
                return "类型填写错误/不规范";
            }
            Datadict typeTdatadict = typeMap.get(type);
            ruleList.setTypeId(typeTdatadict.getItemId());

        }
        if(form!=null){
            Map<String, Datadict> formMap = uploadMapper.queryType(101038);
            if(!formMap.containsKey(form)){
                return "格式填写错误/不规范";
            }
            Datadict formTdatadict = formMap.get(form);
            ruleList.setFormId(formTdatadict.getItemId());
        }
        if(remark!=null){
            if(remark.length() > 100){
                return "备注字数超过规定,长度100";
            }
        }

        return null;
    }

    @Override
    public JSONObject updateListRuleList(List<RuleList> ruleListList) {
        int flag = uploadMapper.updateListRuleList(ruleListList);
        if(flag>0){
            return JSONObject.oK("新增成功");
        }
        return JSONObject.oK("新增失败");
    }
}
